package com.ce.webframework.sec.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.common.vo.OrganizationalStructureVO;
import com.ce.util.BlankUtil;
import com.ce.webframework.sec.service.ISecMsgTipsService;
import com.ce.webframework.sec.util.CommonUtil;
import com.ce.webframework.sec.vo.MsgGlobal;
import com.ce.webframework.sec.vo.SecMsgTipsVO;
import com.ce.webframework.sec.vo.SecUserinfoVO;
import com.sitechasia.webx.core.annotation.Out;
import com.sitechasia.webx.core.exception.UILayerException;
import com.sitechasia.webx.core.utils.base.PopulateUtil;

/**
*
* <p>版权所有：中企动力
* <p>未经本公司许可，不得以任何方式复制或使用本程序任何部分
* <p>功能描述：处理消息提示的action
*
* @author kuanglingxuan
* Created on 2007-7-25
*/
public class MsgTipsAction extends PmsBaseAction{


	private ISecMsgTipsService secMsgTipsService;

	public void setSecMsgTipsService(ISecMsgTipsService secMsgTipsService){
		this.secMsgTipsService = secMsgTipsService;
	}

	/**
	 *	功能描述：处理消息提示请求，组装xml返回
	 */
	public String msgTips(){
//		System.out.println("in msgTips()");
//		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		OrganizationalStructureVO user = getLoginUser(getRequest());
		String usercode = "";
		if(user != null){
//			user = (User)obj;
//			System.out.println("user--->"+user.getUsername());
			//usercode = user.getUsername();//session
			usercode = user.getUserCode();
		}
		MsgGlobal mg =(MsgGlobal) this.getServlet().getServletContext().getAttribute("msgGlobal");

		if(!BlankUtil.isBlank(mg) && BlankUtil.isBlank(mg.getUserCodeList())){//如果启动系统mg对象为空，就从数据库查出用户未读消息的用户编码
			mg = new MsgGlobal();
			mg.setUserCodeList(secMsgTipsService.getCodesNoReadMsg());
			this.getServlet().getServletContext().setAttribute("msgGlobal", mg);
		}

		List userCodeList = mg.getUserCodeList();//Global
//		System.out.println("getMsgGlobal----------->"+mg.getUserCodeList());
//

		List msgList = null;

		String responseStr = "";


		String idStr = getRequest().getParameter("ids");
		if(idStr != null){
			System.out.println("idStr---->"+idStr);
			List<Long> ids = Arrays.asList(CommonUtil.arrayStringToLong(idStr.split(";")));
			secMsgTipsService.updateReadFlag(ids, '1');
		}

		if(userCodeList.contains(usercode)){
			msgList = secMsgTipsService.getMsgTipsList(usercode);
//			System.out.println("getMsgListName---->"+msgList);
			responseStr = this.generateOutputString(msgList);
			userCodeList.remove(usercode);
		}

//		System.out.println("response starting...");
		generateResponse(responseStr);
		return null;

	}

	private void generateResponse(String responseStr){
		byte[] bytes;
		this.getResponse().setHeader("Cache-Control","no-cache");
		this.getResponse().setContentType("text/xml");
		try {
			bytes = responseStr.getBytes("UTF-8");
			this.getResponse().getOutputStream().write(bytes);
		} catch (IOException e) {

			e.printStackTrace();
			throw new UILayerException("UILayerException-----msgTips");
		}
	}

	/**
	 * 功能描述：生成xml字符串
	 * @param msgList
	 * @return xml string
	 */
	private String generateOutputString(List msgList) {

        StringBuffer buffer = new StringBuffer();

        if (msgList != null && msgList.size()>0) {
        	buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        	buffer.append("<msg-list>");
    		for (int i = 0; i < msgList.size(); i++) {
    			SecMsgTipsVO node = (SecMsgTipsVO)msgList.get(i);
    			buffer.append("<msg-node>");
    			buffer.append("<msg-id>"+node.getMsgTipId()+"</msg-id>");
		        buffer.append("<msg-text>"+node.getFormatMsgText()+"</msg-text>");
		        buffer.append("<url>"+node.getUrl()+"</url>");
		        buffer.append("<date-time>"+node.getFormatDateTime()+"</date-time>");
		        buffer.append("</msg-node>");


    		}
    		buffer.append("</msg-list>");
        }

//        System.out.println("returnValue---->"+buffer.toString());
        return buffer.toString();
	}

	public SecMsgTipsVO openEditPage(){
		String ComeUrl = "";
		ComeUrl = this.getRequest().getHeader("REFERER");//取得上一级页面的RUL
		System.out.println("ComeUrlmsg--->"+ComeUrl);

		Enumeration e = getRequest().getHeaderNames();
		while (e.hasMoreElements()) {
		String name = (String)e.nextElement();
		String value = this.getRequest().getHeader(name);
		System.out.println(name + " = " + value);
		}
		SecMsgTipsVO msgVO = new SecMsgTipsVO();
		return msgVO;
	}

	@Out(key = "currentEntity")
	public void edit(){

//		SecMsgTipsVO msgVO = new SecMsgTipsVO();
//
//		System.out.println("text---->"+this.getRequest().getParameter("msgText"));
//		msgVO.setSendTime(new Date());
//		msgVO.setReadFlag('0');//未读
//		PopulateUtil.populate(getRequest(), msgVO);
//		System.out.println("test---->"+msgVO.getMsgText());
//		msgVO.setRemindTime(new Date());
////		Object obj = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
////		User user = null;
//		OrganizationalStructureVO user = getLoginUser();
////		String usercode = "";
//		String usercode = "";
//		if(user != null){
////			user = (User)obj;
//			System.out.println("user--->"+user.getUsername());
//			usercode = user.getUsername();//session
//		}
//		msgVO.setReceiverCode(usercode);
//		System.out.println("secMsgTipsService---->"+secMsgTipsService);
//		secMsgTipsService.addMsgTips(msgVO);
//	/*
//	 消息发送和接收简单过程：
//	 发送方user001产生消息构造MsgNodeVO对象，保存到数据库短消息表。并保存接受方userCode(user002)到在Global对象中的userCodeList中。
//	 接受方user002定时异步访问服务器遍历userCodeList查询是否有user002的新消息，如果存在就删除userCodeList中的user002，并以userCode为查询条件按消息产生时间降序拿到消息集合返回给接受方客户端。
//	 */
//



//		System.out.println("msgVO---->"+msgVO.getMsgText());
	}

	public static void main(String[] args){
		MsgTipsAction m = new MsgTipsAction();
		List ls = new ArrayList();
		SecMsgTipsVO node = new SecMsgTipsVO();
		node.setMsgText("消息的测试消息的测试消111111111241111111111111111111679836011息的测试消息的测试");
		node.setUrl("Manage.tap");
		node.setSendTime(new Date());
		SecMsgTipsVO node1 = new SecMsgTipsVO();
		node1.setMsgText("消息的坏测试1111111111111111111111111111");
		node1.setUrl("Home.tap");
		node1.setSendTime(new Date());
		ls.add(node);
		ls.add(node1);
		m.generateOutputString(ls);
	}
}
